/**
 * 
 */
package com.guzhi.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.guzhi.common.Consts;
import com.guzhi.domain.DomainResource;
import com.guzhi.domain.User;

/**
 * @author duanshao
 * 
 */
@Service
public class UserService {
	
    @Autowired
    private DomainResource resource;

    @Autowired
    private RedisService redis;

    // select b.userId from inter a, inter b where a.userId = 22 and a.friendId
    // = b.friendId and b.friendId != 22 and b.userId != 22 group by b.userId
    public List<User> getUserByIds(List<Long> ids) {
        List<String> userIdList = new ArrayList<String>();
        for (Long id : ids) { 
            userIdList.add(Consts.Cache.USER_PREFIX + id);
        }
        //5,6
        List<User> users = redis.batchGet(userIdList, User.class);
        List<Long> getedIds = new ArrayList<Long>();
        for (User u : users) {
                getedIds.add(u.getId());
        }
        ids.removeAll(getedIds);
        if (ids.size() > 0) {
            List<User> dbUsers = resource.batchGetUser(ids);
            users.addAll(dbUsers);
        }
        return users;
    }

    public User getUserById(Long id) {
        String key = Consts.Cache.USER_PREFIX + id;
        User user = redis.get(key, User.class);
        if (user == null) {
            user = resource.getUserById(id);
            if (user != null) {
                redis.set(key, user);
            }
        }
        return user;
    }
}
